import json

from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone
from django.views import View
from i_home.utils.Compress_picture import compress_picture
from i_home.utils.view import LoginRequiredMixin
from order.models import Order
from houses.models import House, Area, Facility, HouseImage


#城区列表

class AreasView(View):
    def get(self, request):
        # 从MySQL数据库tb_user表中获取areas
        areas = Area.objects.filter(name__isnull=False)
        # 创建列表保存城区信息
        data = []
        for area in areas:
            data.append({'aid': area.id,
                         'aname': area.name})
        # 返回前端
        return JsonResponse({'errmsg': '获取成功',
                             'errno': '0',
                             'data': data})


# 发布房源
class HouseReleaseView(View):

    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body)
        price = json_dict.get('price')
        title = json_dict.get('title')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facilitys = json_dict.get('facility')
        # 整体校验
        if not all([price, title, area_id, address,
                    room_count, acreage, unit, capacity,
                    beds, min_days, facilitys]):
            return JsonResponse({'errno': 4001,
                                 'errmsg': 'NODATA'})
        # 单个校验id=request.user
        if House.objects.filter(id=1,
                                area_id=area_id,
                                address=address):
            return JsonResponse({'errno': '4003',
                                 'errmsg': 'DATAEXIST'})
        try:
            area = Area.objects.get(id=area_id)
        except Exception as e:
            return JsonResponse({'errno': '4001',
                                 'errmsg': 'DBERR'})
        if not int(deposit) >= 0:
            return JsonResponse({'errno': '4004',
                                 'errmsg': 'DATAERR'})
        if not int(max_days) >= 0:
            return JsonResponse({'errno': '4004',
                                 'errmsg': 'DATAERR'})
        # 将房屋信息保存到数据库
        house = House.objects.create(user=request.user,
                                     area=area,
                                     title=title,
                                     price=int(price)*100,
                                     address=address,
                                     room_count=room_count,
                                     acreage=acreage,
                                     unit=unit,
                                     capacity=capacity,
                                     beds=beds,
                                     deposit=deposit,
                                     min_days=min_days,
                                     max_days=max_days,
                                     )
        # 多对多
        for fac_id in facilitys:
            facility = Facility.objects.get(id=fac_id)
            facility.house_set.add(house)

            # 返回前端
        return JsonResponse({'errno': '0',
                             'errmsg': '发布成功',
                             'data': {'house_id': house.id}})


    def get(self, request):
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p', 1)
        data_list = []
        houses_list = []
        houses = House.objects.all()[:int(p)]
        if sk in ["new", "booking", "price-des", "price-inc"]:
            sort_dict ={
                "new": "create_time",
                "booking" : "-order_count",
                "price-des" : "-price",
                "price-inc": "price",
            }
            houses = House.objects.all().order_by(sort_dict[sk])

        if aid:
            houses = House.objects.filter(area_id=aid)
        for house in houses:
            houses_list.append(house.id)
        houses_list = list(set(houses_list))
        if ed and sd:
            h_id1 = Order.objects.filter(Q(begin_date__gt=ed)|Q(end_date__lt=sd),status__in=[3,4,5,6])
            houses_list = []
            for i in h_id1:
                houses_list.append(i.house.id)
                houses_list = list(set(houses_list))



        for house_id in houses_list:
            house = House.objects.get(id = house_id)
            url = house.index_image_url
            ctime = house.create_time
            data_list.append({
                "aid": aid,
                "address": house.address,
                "area_name": house.area.name,
                "ctime": ctime,
                "house_id": house.id,
                "img_url": str(url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(house.user.avatar)
            })

        data_dict = {}
        data_dict['houses'] = data_list
        data_dict['total_page'] = p
        # 拼接参数, 返回
        return JsonResponse({"data": data_dict,
                             "errmsg": "请求成功",
                             "errno": 0})


# 生成房屋图片
class GenerateHouseImage(LoginRequiredMixin, View):
    def post(self, request, house_id):
        img = request.FILES.get('house_image')

        image_url, ret = compress_picture(img)

        try:
            HouseImage.objects.create(house_id=house_id, url=image_url)
            house = House.objects.get(id=house_id)
            house.index_image_url = image_url
            house.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '上传失败'})
        dict = {}
        dict['url'] = image_url
        return JsonResponse({'data': dict, 'errno': '0',
                             'errmsg': '头像上传成功'})


# 房屋详情
class HouseDetailsView(View):
    def get(self, request, house_id):

        if request.user.is_authenticated:
            user_id = request.user.id
        else:
            user_id = '-1'

        try:
            house = House.objects.get(id=house_id)
            house_images = HouseImage.objects.filter(house_id=house_id)
            orders = Order.objects.filter(house_id=house_id, status__in=(4,6))
            facilities = house.facility.all()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        comments_list = []
        for order in orders:
            comments_list.append({
                "comment": order.comment,
                "ctime": order.end_date,
                "user_name": order.user.real_name
            })

        facilities_list = []
        for facility in facilities:
            facilities_list.append(facility.id)

        img_url_list = []
        for image_url in house_images:
            img_url_list.append(image_url.url)

        house_dict = {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": comments_list,
            "deposit": house.deposit,
            "facilities": facilities_list,
            "hid": house_id,
            "img_urls": img_url_list,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": str(house.user.avatar),
            "user_id": house.user.id,
            "user_name": house.user.mobile
        }

        data = {
            "house": house_dict,
            "user_id": user_id
        }
        return JsonResponse({"data": data, "errmsg": "OK",
                             "errno": "0"})


#我的房屋列表
class MyhouseListView(LoginRequiredMixin,View):

    def get(self,request):
        list = []
        try:
            # 从House表中获取查询集数据
            houses = House.objects.filter(user=request.user)

        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '获取数据失败'})
        #循环得到单一数据，并按要求挨个添加到列表中
        for house in houses:
            list.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": timezone.localtime(house.create_time).strftime("%Y-%m-%d %H:%M:%S"),
                "house_id": house.id,
                "img_url": str(house.index_image_url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": str(house.user.avatar)
            })

        # 构建字典
        data = {}
        data['houses'] = list

        # 返回数据
        return JsonResponse({'errno': 0,
                             'errmsg': 'ok',
                             'data': data})

# 房屋首页
class HouseIndexView(View):

    def get(self, request):
        houses = House.objects.all().order_by("-create_time")[:5]
        data_list = []
        for house in houses:
            data_list.append({
                'house_id': house.id,
                'img_url': house.index_image_url,
                'title': house.title
            })

        return JsonResponse({
            "data": data_list,
            "errmsg": "ok",
            "errno": 0
        })
